const express = require('express');
const Users = require('../models/users');
const jwt = require('jsonwebtoken');
const cookieParser = require('cookie-parser');
const secret = 'abc';
const router = new express.Router();
router.use(cookieParser());

router.post('/register', async (req, res) => {
    console.log(req.body);
    const {
        user_name,
        password
    } = req.body;

    const user_name_reg = /^[A-z0-9]{3,12}$/;
    const password_reg = /^[A-z0-9]{3,12}$/;

    if (user_name_reg.test(user_name.trim()) && password_reg.test(password.trim())) {
        const result_find = await Users.findOne({
            user_name
        });

        console.log(result_find);
        if (result_find) {
            res.send('用户名已存在');
        } else {
            const result = await Users.create({
                user_name,
                password
            });
            console.log(result);
        }

    } else {
        res.send('用户名或者密码不配！！')
    }
});
router.post('/login', async (req, res) => {
    const user = req.body;
    const result = await Users.findOne({
        user_name: user.user_name
    }, {
        _id: 0,
        __v: 0
    });
    console.log(result);
    if (result) {
        if (user.user_name == result.user_name && user.password == result.password) {
            jwt.sign(user, secret, {
                expiresIn: '1h'
            }, (err, token) => {
                if (!err) {
                    console.log(token);
                    res.cookie('token', token, {
                        maxAge: 1000 * 60 * 60
                    })
                    res.send('登录成功！！');
                } else {
                    console.log(err);
                    res.send('用户名或密码错误');
                }
            })

        } else {
            res.send('用户名或密码错误');
        }
    } else {
        res.send('用户名或密码错误');
    }




})
router.get('/tokenTest', (req, res) => {
    console.log(req.cookies);
    jwt.verify(req.cookies.token, secret, (err, data) => {
        if (!err) {
            console.log(data);
            res.send('获取到cookies');
        } else {
            console.log(err);
            res.send('请去登录页面重新登录！！');
        }
    })
})
module.exports = router;